﻿using D.B.Data.API.Applications.Command.RoleCommand;
using D.B.Data.Domain;
using D.B.Data.ErrorCode;
using D.B.Data.Infrastructuse;
using MediatR;
using Microsoft.EntityFrameworkCore;

namespace D.B.Data.API.Applications.CommandHandler.RoleCommandHandler
{
    public class AddRoleUserCommandHandler : IRequestHandler<AddRoleUserCommand, APIResult<object>>
    {
        private readonly IBaseRepository<UserRoleModel> baseRepository;
        private readonly IBaseRepository<UserModel> userRepository;
        private readonly DataDbContext dbContext;

        public AddRoleUserCommandHandler(IBaseRepository<UserRoleModel> baseRepository, IBaseRepository<UserModel> userRepository, DataDbContext dbContext)
        {
            this.baseRepository = baseRepository;
            this.userRepository = userRepository;
            this.dbContext = dbContext;
        }

  

        public Task<APIResult<object>> Handle(AddRoleUserCommand request, CancellationToken cancellationToken)
        {
            // 获取同步执行策略（关键：用Execute而非ExecuteAsync）
            var executionStrategy = dbContext.Database.CreateExecutionStrategy();

            // 执行同步事务逻辑
            var result = executionStrategy.Execute(() =>
            {
                using var transaction = dbContext.Database.BeginTransaction(); // 同步开启事务
                try
                {
                    var DeptListId = userRepository.GetAll().Where(s => s.DeptId == request.DeptId).Select(s => s.Id);



                    //删除
                    var res = baseRepository.GetAll().Where(s => s.RoleId == request.RoleId && DeptListId.Contains(s.UserId)).ToList();

                    baseRepository.Del(res);
                    List<UserRoleModel> model = new List<UserRoleModel>();

                    var list = request.UserId.Split(',').ToList();
                    foreach (var item in list)
                    {
                        if (Convert.ToInt64(item) == 0)
                            continue;
                        model.Add(new UserRoleModel()
                        {

                            CreateUserId = request.CreateId,
                            UserId = Convert.ToInt64(item),
                            RoleId = request.RoleId,
                        });


                    }

                    int count = baseRepository.Add(model);
                    APIResult<object> result = new APIResult<object>();
                    if (count > 0)
                    {
                        result.Code = EnumCode.Ok;
                        result.Msg = "分配成功";

                    }
                    else
                    {
                        result.Code = EnumCode.File;
                        result.Msg = "分配失败";
                    }

                    // 5. 提交事务
                    transaction.Commit();

                    return new APIResult<object>
                    {
                        Code = EnumCode.Ok,
                        Msg = "分配成功"
                    };
                }
                catch (Exception ex)
                {
                    transaction.Rollback(); // 同步回滚
                    return new APIResult<object>
                    {
                        Code = EnumCode.Ok,
                        Msg = $"分配失败：{ex.Message}"
                    };
                }
            });

            // 将同步结果包装为Task返回（因接口要求返回Task）
            return Task.FromResult(result);
        }
    }
}

